"""
让大模型自动调用工具
1.定义工具
2.大模型绑定工具 bind_tools
3.大模型预调用工具
4.解析工具信息(str) tool_calls
5.将str工具转换可调用 eval工具,并执行函数
6.大模型润色工具输出的结果
"""

from model_utils import getLLM
from typing import Annotated
from langchain.tools import tool

llm = getLLM()

@tool
def get_weather(city :Annotated[str, "城市名字"]):
    """查询城市天气工具"""
    if(city=="上海"):
        return "小雨转晴"
    return "特大暴雨"

#大模型绑定工具
llm_with_tools = llm.bind_tools([get_weather])

msg = [
    ("system","请回答用户问题"),
    ("human","成都天气如何")
]
#工具预调用
m = llm_with_tools.invoke(msg)
print(m.tool_calls)

if m.tool_calls is not None and len(m.tool_calls)>0:
    msg.append(m)
    for tool_info in m.tool_calls:
        fn_name = tool_info["name"]
        fn_args = tool_info["args"]
        fn = eval(fn_name)
        r = fn.invoke(fn_args)
        msg.append(r)

print(msg)
r = llm.invoke(msg)
print(r)